﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Aliyun.OSS.Common.Internal;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using SelfService.Model.Models;
using TT;
using WalkingTec.Mvvm.Core.Support.FileHandlers;


namespace SelfService.ViewModel.SysDeviceVMs
{
    public partial class SysDeviceVm : BaseCRUDVM<SysDevice>
    {

        public SysDeviceVm()
        {
            SetInclude(x => x.Group);
            SetInclude(x => x.DllZip);
        }

        [DisplayName("DLL压缩文件")]
        public string DllZipName { get; set; }

        protected override void InitVM()
        {
            if (Entity.DllZipId != null)
            {
                var file = DC.Set<FileAttachment>().FirstOrDefault(e => e.ID == Entity.DllZipId);
                if (file != null)
                {
                    DllZipName = file.FileName;
                }
            }
            if (Entity.DllZip != null)
            {
                Entity.DllZip.DataStream = default;
                Entity.DllZip.FileData = default;
            }
        }

        public override void DoAdd()
        {
            if (Entity.DllZipId != null)
            {
                var scope = Wtm.ServiceProvider.CreateScope();
                var fileProvider = scope.ServiceProvider.GetRequiredService<WtmFileProvider>();
                var file = fileProvider.GetFile(Entity.DllZipId.ToString(), true, Wtm.DC);
                if (file != null)
                {
                    Entity.DllHash = Md5Hash(file.DataStream);
                }
            }
            base.DoAdd();
        }

        private string Md5Hash(Stream stream)
        {
            using var md5 = MD5.Create();
            var hash = md5.ComputeHash(stream);
            var stringBuilder = new StringBuilder();
            foreach (var num in hash)
                stringBuilder.Append(num.ToString("x2"));
            return stringBuilder.ToString();
        }

        public override void DoEdit(bool updateAllFields = false)
        {
            if (Entity.DllZipId != null)
            {
                var scope = Wtm.ServiceProvider.CreateScope();
                var fileProvider = scope.ServiceProvider.GetRequiredService<WtmFileProvider>();
                var file = fileProvider.GetFile(Entity.DllZipId.ToString(), true, Wtm.DC);
                if (file != null)
                {
                    Entity.DllHash = Md5Hash(file.DataStream);
                }
            }
            base.DoEdit(updateAllFields);
        }

        public override void DoDelete()
        {
            base.DoDelete();
        }


    }
}
